package security.dao;

import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import security.model.Session;


@Stateless
public class SessionDAO {

	
	@PersistenceContext(unitName = "persistence")
    private EntityManager em;
	
	
	public Session getById(Integer id){	
		return em.find(Session.class, id);
	}
	
    public Session save(Session session) {
    	em.persist(session);
    	return session;
    }
    
    public Session update(Session session) {
    	return em.merge(session);
    }
    
    public void delete(Integer id) {
    	em.remove(em.find(Session.class, id));
    }
		
	@SuppressWarnings("unchecked")
    public List<Session> list(int first,int max) {    	
    	Query query = em.createQuery("SELECT e FROM Session");
    	if (max > 0) {
            query.setMaxResults(max);
        }
        if (first > 0) {
            query.setFirstResult(first);
        }
        return query.getResultList();   
    }
    
    
    // ------------------------------------------------------------------------------
    
    public Session getByToken(String token) {    	
    	Session result = null;
    	Query query = em.createQuery("SELECT e FROM Session e WHERE e.token=:token");
    	query.setParameter("token", token);
    	try {
    		result = (Session) query.getSingleResult();   
        }
    	catch (NoResultException e) {
			//e.printStackTrace();
		}
        return result;
    }
    
    
}

